package com.qyhl.webtv.module_news.news.video;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.sdk.statisticssdk.StatisticsMainInit;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.decoration.RecycleViewDivider;
import com.orhanobut.hawk.Hawk;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.NotchSizeUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.LoadingDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.constant.AppConfigConstant;
import com.qyhl.webtv.commonlib.entity.intergral.CoinBean;
import com.qyhl.webtv.commonlib.entity.news.GlobalNewsBean;
import com.qyhl.webtv.commonlib.entity.news.NormalNewsBean;
import com.qyhl.webtv.commonlib.item.ItemAdvCommon;
import com.qyhl.webtv.commonlib.item.ItemAdvGroup;
import com.qyhl.webtv.commonlib.item.ItemAdvLarge;
import com.qyhl.webtv.commonlib.item.ItemCatchNews;
import com.qyhl.webtv.commonlib.item.ItemCirclePicture;
import com.qyhl.webtv.commonlib.item.ItemCircleText;
import com.qyhl.webtv.commonlib.item.ItemCircleTopic;
import com.qyhl.webtv.commonlib.item.ItemCircleVideo;
import com.qyhl.webtv.commonlib.item.ItemCommonLarge;
import com.qyhl.webtv.commonlib.item.ItemCommonLeft;
import com.qyhl.webtv.commonlib.item.ItemCommonRight;
import com.qyhl.webtv.commonlib.item.ItemCommonThreePics;
import com.qyhl.webtv.commonlib.item.ItemGoodLife;
import com.qyhl.webtv.commonlib.item.ItemNoPicture;
import com.qyhl.webtv.commonlib.item.ItemOtherAdv;
import com.qyhl.webtv.commonlib.item.ItemPicture;
import com.qyhl.webtv.commonlib.item.ItemScoop;
import com.qyhl.webtv.commonlib.item.ItemScoopTopic;
import com.qyhl.webtv.commonlib.item.ItemSmallVideo;
import com.qyhl.webtv.commonlib.item.ItemTeleText;
import com.qyhl.webtv.commonlib.item.ItemTitleNews;
import com.qyhl.webtv.commonlib.item.ItemTopNews;
import com.qyhl.webtv.commonlib.item.ItemTopNoPicture;
import com.qyhl.webtv.commonlib.item.ItemUnion;
import com.qyhl.webtv.commonlib.item.ItemVideoLarge;
import com.qyhl.webtv.commonlib.item.ItemVideoLeft;
import com.qyhl.webtv.commonlib.item.ItemVideoRight;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.ItemSkipUtils;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.cache.SpfManager;
import com.qyhl.webtv.commonlib.utils.coin.GoldCoinTimeView;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.editbar.EditBar;
import com.qyhl.webtv.commonlib.utils.view.editbar.EditBarOnClickListenerImpl;
import com.qyhl.webtv.commonlib.utils.view.video.detailvideo.QYVideoPlayer;
import com.qyhl.webtv.module_news.utils.NewsConstant;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.utils.GSYVideoHelper;
import com.shuyu.gsyvideoplayer.utils.GSYVideoType;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareAPI;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2017/12/7.
 *
 * @author cookie_zj
 * 视频新闻
 */

@Route(path = ARouterPathConstant.VIDEO_NEWS_ACTIVITY)
public class VideoNewsActivity extends BaseActivity implements VideoNewsContract.VideoNewsView {
    @BindView(R2.id.editbar)
    EditBar editbar;
    @BindView(R2.id.video_player)
    QYVideoPlayer videoPlayer;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.coin_time_view)
    GoldCoinTimeView coinTimeView;
    @BindView(R2.id.coin_layout)
    CardView coinLayout;
    @BindView(R2.id.coin_login_tips)
    ImageView coinLoginTips;


    private TextView summary;
    private LinearLayout extendLayout;
    private TextView orgin;
    private TextView date;
    private TextView author;
    private TextView scan;

    private TextView videoNewsTitle;

    private VideoNewsPresenter mPresenter;

    String newsId;

    private MultiItemTypeAdapter<GlobalNewsBean> mAdapter;

    private List<GlobalNewsBean> mDataList; //转换后的拓展新闻数据

    private NormalNewsBean mBean;

    private boolean editbarEnable = true;
    private boolean collectEnable = true;

    private LoadingDialog.Builder builder;
    private HeaderAndFooterWrapper headerAndFooterWrapper;
    /**
     * 是否为刘海屏
     */
    private boolean isNotch;

    private boolean isLimited = false;

    private boolean isFirst = true;

    private boolean isCurFirst = true;

    private String integralSwitch;

    private int collectNum;

    private int shareNum;

    private int commentNum;

    private boolean isCollect;

    private int follows = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BusFactory.getBus().register(this);
        isNotch = NotchSizeUtil.hasNotchInScene(this);
        if (!isNotch) {
            if (Build.VERSION.SDK_INT > 19) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
        }

    }

    @Override
    protected int getContentView() {
        return R.layout.news_activity_news_video;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {

    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new VideoNewsPresenter(this);
        integralSwitch = CommonUtils.getInstance().getIntergralSwitch();
        newsId = getIntent().getStringExtra("id");
        initView();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void setListener() {
        setListeners();
        mPresenter.getDetail(newsId);
        mPresenter.count(newsId);
    }


    /**
     * 初始化
     */
    public void initView() {
        loadMask.setStatus(LoadingLayout.Loading);

        mDataList = new ArrayList<>();

        @SuppressLint("InflateParams") View headerView = LayoutInflater.from(this).inflate(R.layout.news_header_news_video, null);
        summary = (TextView) headerView.findViewById(R.id.summary);
        extendLayout = (LinearLayout) headerView.findViewById(R.id.extend_layout);
        orgin = (TextView) headerView.findViewById(R.id.orgin);
        date = (TextView) headerView.findViewById(R.id.date);
        scan = (TextView) headerView.findViewById(R.id.scan);
        author = (TextView) headerView.findViewById(R.id.author);
        videoNewsTitle = (TextView) headerView.findViewById(R.id.video_news_title);


        builder = new LoadingDialog.Builder(VideoNewsActivity.this);
        builder.setTitle("请稍等...");
        builder.setCanceledOnTouchOutside(false);
        builder.setCancelable(true);


        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);

        recyclerView.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, 1, ContextCompat.getColor(this, R.color.global_gray_lv3)));


        //配置适配器
        mAdapter = new MultiItemTypeAdapter<GlobalNewsBean>(this, mDataList);
        mAdapter.addItemViewDelegate(new ItemAdvCommon(this));
        mAdapter.addItemViewDelegate(new ItemAdvGroup(this));
        mAdapter.addItemViewDelegate(new ItemAdvLarge(this));
        mAdapter.addItemViewDelegate(new ItemCatchNews(this));
        mAdapter.addItemViewDelegate(new ItemCommonLarge(this));
        mAdapter.addItemViewDelegate(new ItemCommonRight(this));
        mAdapter.addItemViewDelegate(new ItemCommonLeft(this));
        mAdapter.addItemViewDelegate(new ItemGoodLife(this));
        mAdapter.addItemViewDelegate(new ItemNoPicture(this));
        mAdapter.addItemViewDelegate(new ItemPicture(this));
        mAdapter.addItemViewDelegate(new ItemTitleNews(this));
        mAdapter.addItemViewDelegate(new ItemTopNews(this));
        mAdapter.addItemViewDelegate(new ItemTopNoPicture(this));
        mAdapter.addItemViewDelegate(new ItemVideoLarge(this));
        mAdapter.addItemViewDelegate(new ItemVideoLeft(this));
        mAdapter.addItemViewDelegate(new ItemVideoRight(this));
        mAdapter.addItemViewDelegate(new ItemSmallVideo(this));
        mAdapter.addItemViewDelegate(new ItemUnion(this));
        mAdapter.addItemViewDelegate(new ItemTeleText(this));
        mAdapter.addItemViewDelegate(new ItemCommonThreePics(this));
        mAdapter.addItemViewDelegate(new ItemCircleVideo(this));
        mAdapter.addItemViewDelegate(new ItemCirclePicture(this));
        mAdapter.addItemViewDelegate(new ItemCircleText());
        mAdapter.addItemViewDelegate(new ItemCircleTopic(this));
        mAdapter.addItemViewDelegate(new ItemScoop());
        mAdapter.addItemViewDelegate(new ItemScoopTopic());
        mAdapter.addItemViewDelegate(new ItemOtherAdv(VideoNewsActivity.this));
        headerAndFooterWrapper = new HeaderAndFooterWrapper(mAdapter);
        headerAndFooterWrapper.addHeaderView(headerView);
        recyclerView.setAdapter(headerAndFooterWrapper);

        editbar.hidePraise(false);

    }

    /**
     * 设置监听
     */
    public void setListeners() {
        coinTimeView.setOnClickListener(v -> RouterManager.router(ARouterPathConstant.ANTIC));

        //重新加载
        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("加载中...");
            mPresenter.getDetail(newsId);
        });

        //评论栏
        editbar.setEditBarOnClickListener(new EditBarOnClickListenerImpl() {
            @Override
            public void onSend() {
                if (editbarEnable) {
                    editbarEnable = false;
                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                        @Override
                        public void login(boolean isLogin) {
                            if (isLogin) {
                                String content = editbar.getContent();
                                if (StringUtils.isEmpty(content)) {
                                    Toasty.normal(VideoNewsActivity.this, "评论内容不能为空！", Toast.LENGTH_SHORT).show();
                                    editbarEnable = true;
                                } else {
                                    String nickName = CommonUtils.getInstance().getNickName();
                                    mPresenter.sendComment(mBean.getTitle(), mBean.getCatalogID(), "1", mBean.getID(), nickName, content);
                                    hideInput();//隐藏软键盘
                                    editbar.clearContent();
                                }
                            } else {
                                Toasty.normal(VideoNewsActivity.this, "尚未登录或登录已失效！", Toast.LENGTH_SHORT).show();
                                RouterManager.routerLogin(VideoNewsActivity.this, 0);
                                editbarEnable = true;
                            }
                        }

                        @Override
                        public void error(String s) {
                            editbarEnable = true;
                        }
                    });

                }
            }

            @Override
            public void onShare() {
                MPermissionUtils.requestPermissionsResult(VideoNewsActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        MShareBoard shareBoard = new MShareBoard(VideoNewsActivity.this, newsId, mBean.getTitle(), mBean.getLogo(), "", 16, CommonUtils.getInstance().getBannerId(), true);
                        shareBoard.setShareCallBack(new MShareBoard.ShareCallBack() {
                            @Override
                            public void callBack() {
                                shareNum++;
                                editbar.setShareNum(shareNum);
                                mPresenter.shareCount(newsId);
                            }
                        });
                        shareBoard.showPopupWindow();
                    }

                    @Override
                    public void onPermissionDenied() {
                        MPermissionUtils.showTipsDialog(VideoNewsActivity.this);
                    }
                });
            }

            @Override
            public void onCollect(final boolean isCollect) {
                if (collectEnable) {
                    collectEnable = false;
                    builder.show();

                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                        @Override
                        public void login(boolean isLogin) {
                            if (isLogin) {
                                if (isCollect) {
                                    mPresenter.collect(newsId);
                                } else {
                                    mPresenter.cancelCollect(newsId);
                                }
                            } else {
                                builder.dismiss();
                                RouterManager.routerLogin(VideoNewsActivity.this, 0);
                                collectEnable = true;
                            }
                        }

                        @Override
                        public void error(String s) {
                            collectEnable = true;
                        }
                    });
                }

            }

            @Override
            public void onComment() {
                Bundle bundle = new Bundle();
                bundle.putString("id", mBean.getID());
                bundle.putString("sectionId", mBean.getCatalogID());
                bundle.putString("title", mBean.getTitle());
                RouterManager.router(ARouterPathConstant.NEWS_COMMENT, bundle);
            }

            @Override
            public void doPraise(boolean isPraised) {
                CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                    @Override
                    public void login(boolean isLogin) {
                        if (isLogin) {
                            if (isPraised) {
                                mPresenter.cancelLike(newsId);
                            } else {
                                mPresenter.like(newsId);
                            }
                        } else {
                            builder.dismiss();
                            editbar.isPraise(false);
                            RouterManager.routerLogin(VideoNewsActivity.this, 0);
                        }
                    }

                    @Override
                    public void error(String s) {

                    }
                });
            }
        });

        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                GlobalNewsBean bean = mDataList.get(position - 1);
                ItemSkipUtils.getInstance().itemSkip(bean, VideoNewsActivity.this, view);
                if (CommonUtils.getInstance().getHasHistory()) {
                    //设置已读，保存记录于本地
                    Map<String, String> historyMap;
                    if (Hawk.contains("readHistory")) {
                        historyMap = CommonUtils.getInstance().getReadHistory();
                    } else {
                        historyMap = new HashMap<>();
                    }
                    historyMap.put(bean.getNewsId(), DateUtils.getCurrentTime());
                    CommonUtils.getInstance().putConfigData(AppConfigConstant.READ_HISTORY, historyMap);
                    Hawk.put("readHistory", historyMap);
                    headerAndFooterWrapper.notifyItemChanged(position);
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });


        builder.getmDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
            }
        });

        if (integralSwitch.equals("1")) {
            coinLayout.setVisibility(View.VISIBLE);
            coinTimeView.setOnTimeoutListener(new GoldCoinTimeView.OnTimeoutListener() {
                @Override
                public void timeout() {
                    if (Hawk.contains("login")) {
                        String userName = CommonUtils.getInstance().getUserName();
                        mPresenter.getCoin(userName);
                    } else if (isFirst) {
                        coinLoginTips.setVisibility(View.GONE);
                        isFirst = false;
                        isCurFirst = false;
                        coinTimeView.stopTime();
                        coinTimeView.resetMax();
                    } else {
                        coinTimeView.stopTime();
                        isCurFirst = false;
                        coinTimeView.resetMax();
                    }
                }

                @Override
                public void limit() {
                    coinTimeView.stopTime();
                    isLimited = true;
                }
            });

            videoPlayer.setPlayerListener(new QYVideoPlayer.PlayerListener() {
                @Override
                public void isPlay(boolean isPlay) {
                    if (Hawk.contains("login") || isFirst || isCurFirst) {
                        if (isPlay) {
                            coinTimeView.beginTime();
                        } else {
                            coinTimeView.stopTime();
                        }
                    }

                }
            });
        } else {
            coinLayout.setVisibility(View.GONE);
        }


    }

    /**
     * 设置详情
     *
     * @param bean
     */
    @Override
    public void setDetail(NormalNewsBean bean) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~~");
        mBean = bean;

        //四川融媒统计
        if ((CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145)) {
            StatisticsMainInit.newsInfoVisit(CommonUtils.getInstance().getUserName(), mBean.getID(), mBean.getTitle(), mBean.getReferName(), "0");
        }

        //设置标题
        if (StringUtils.isEmpty(mBean.getTitle())) {
            videoNewsTitle.setVisibility(View.GONE);
        } else {
            videoNewsTitle.setVisibility(View.VISIBLE);
            videoNewsTitle.setText(mBean.getTitle());
        }
        //设置作者
        author.setText(mBean.getWriter());

        orgin.setText(mBean.getReferName());
        //设置发布时间
        date.setText(DateUtils.detailDateTranslate(mBean.getPublishDate()));
        //设置浏览数
        try {
            int minPlay = Integer.parseInt(CommonUtils.getInstance().getMinPlay());
            if (minPlay == 0) {
                scan.setVisibility(View.GONE);
            } else {
                //判断评论数是否大于最少浏览数
                if (StringUtils.isEmpty(mBean.getHitCount())) {
                    scan.setVisibility(View.GONE);
                } else if (Integer.parseInt(mBean.getHitCount()) >=
                        minPlay) {
                    scan.setText(StringUtils.transformNum(mBean.getHitCount()));
                    scan.setVisibility(View.VISIBLE);
                } else {
                    scan.setVisibility(View.GONE);
                }
            }

        } catch (Exception e) {
            scan.setVisibility(View.GONE);
        }
        //设置摘要
        if (StringUtils.isNotEmpty(mBean.getSummary())) {
            summary.setVisibility(View.VISIBLE);
            summary.setText(mBean.getSummary());
        } else {
            summary.setVisibility(View.GONE);
        }

        //是否收藏
        isCollect = StringUtils.isNotEmpty(mBean.getIscollect()) && "1".equals(mBean.getIscollect());
        editbar.setCollect(isCollect);

        collectNum = bean.getCollectCount();
        editbar.setCollectNum(collectNum);

        shareNum = StringUtils.isEmpty(bean.getShareCount()) ? 0 : Integer.parseInt(bean.getShareCount());
        editbar.setShareNum(shareNum);

        commentNum = bean.getCounts();
        editbar.setCommentNum(commentNum);

        //是否喜欢
        if (StringUtils.isEmpty(mBean.getGoodViewCount())) {
            follows = 0;
        } else {
            follows = Integer.parseInt(mBean.getGoodViewCount());
        }


        setExtend(mBean.getActiveArticle());//设置延伸新闻


        ImageView imageView = new ImageView(this);
        Glide.with(this)
                .load(mBean.getLogo())
                .apply(new RequestOptions().centerCrop().error(R.drawable.icon_live_no_img).placeholder(R.drawable.icon_live_no_img))
                .into(imageView);
        GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_16_9);
        videoPlayer.setThumbImageView(imageView);//设置封面图
        videoPlayer.setRotateViewAuto(false);
        videoPlayer.setLockLand(true);
        videoPlayer.setMode(QYVideoPlayer.PlayMode.NORMAL);
        videoPlayer.setShowFullAnimation(false);
        videoPlayer.setUp(mBean.getPlayerpath() == null ? "" : mBean.getPlayerpath(), true, "");
        videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
                videoPlayer.startWindowFullscreen(VideoNewsActivity.this, true, true);
            }
        });


        videoPlayer.setStateListener(new QYVideoPlayer.StateListener() {
            @Override
            public void state(boolean isShow) {
                if (isShow) {
                    if (Build.VERSION.SDK_INT > 19) {
                        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
                    }
                } else {
                    if (Build.VERSION.SDK_INT > 19) {
                        getWindow().getDecorView().setSystemUiVisibility(View.INVISIBLE);
                    }
                }
            }

            @Override
            public void closeRadio() {

            }
        });

        videoPlayer.getBackButton().setOnClickListener(v -> finish());

        videoPlayer.getStartButton().performClick();//自动播放
    }


    /**
     * 设置延伸阅读
     *
     * @param beanList
     */
    private void setExtend(List<NormalNewsBean.ActiveAiticle> beanList) {
        if (beanList != null && beanList.size() > 0) {
            extendLayout.setVisibility(View.VISIBLE);
            int globalCommon = Integer.parseInt(CommonUtils.getInstance().getGlobalCommon());
            int globalVideo = Integer.parseInt(CommonUtils.getInstance().getGlobalVideo());
            for (int i = 0; i < beanList.size(); i++) {
                if ("1".equalsIgnoreCase(beanList.get(i).getType()) || "5".equalsIgnoreCase(beanList.get(i).getType())) {
                    beanList.get(i).setCommonStyle(globalCommon);
                    beanList.get(i).setVideoStyle(globalVideo);
                }
            }

            final List<GlobalNewsBean> indexList = new ArrayList<>();
            for (int i = 0; i < beanList.size(); i++) {
                NormalNewsBean.ActiveAiticle bean = beanList.get(i);
                boolean hasPicture = StringUtils.isPictureSuccess(bean.getLogo());
                String type = "", pOne = "", pTwo = "", pThree = "";
                int style = 0;
                switch (bean.getType()) {
                    case "1"://普通新闻
                        type = "1";
                        switch (bean.getPluralPicsFlag()) {
                            case 0:
                                style = bean.getCommonStyle();
                                break;
                            case 1://三图
                                hasPicture = false;
                                if (bean.getImagess().size() == 1) {
                                    hasPicture = true;
                                    pOne = bean.getImagess().get(0).getImageUrlString();
                                } else if (bean.getImagess().size() == 2) {
                                    pOne = bean.getImagess().get(0).getImageUrlString();
                                    pTwo = bean.getImagess().get(1).getImageUrlString();
                                    hasPicture = true;
                                } else if (bean.getImagess().size() >= 3) {
                                    pOne = bean.getImagess().get(0).getImageUrlString();
                                    pTwo = bean.getImagess().get(1).getImageUrlString();
                                    pThree = bean.getImagess().get(2).getImageUrlString();
                                    hasPicture = true;
                                } else {
                                    hasPicture = false;
                                }
                                style = 4;
                                break;
                            case 2:
                                style = 3;
                                break;
                            default:
                                style = bean.getCommonStyle();
                                break;
                        }
                        break;
                    case "2"://图片新闻
                        type = "2";
                        if (bean.getImagess().size() == 1) {
                            pOne = bean.getImagess().get(0).getImageUrlString();
                            hasPicture = true;
                        } else if (bean.getImagess().size() == 2) {
                            pOne = bean.getImagess().get(0).getImageUrlString();
                            pTwo = bean.getImagess().get(1).getImageUrlString();
                            hasPicture = true;
                        } else {
                            pOne = bean.getImagess().get(0).getImageUrlString();
                            pTwo = bean.getImagess().get(1).getImageUrlString();
                            pThree = bean.getImagess().get(2).getImageUrlString();
                            hasPicture = true;
                        }
                        break;
                    case "3"://直播
                        type = "9";
                        break;
                    case "4"://标题新闻
                        type = "8";
                        break;
                    case "5"://视频新闻
                        type = "3";
//                        style = bean.getVideoStyle();
                        style = 1;
                        break;
                    case "8"://互动直播
                        bean.setID(bean.getRoomId());//将roomId设置成通用Id
                        type = "5";
                        break;
                    case "101"://抓取新闻
                        type = "10";
                        break;
                    default:
                        break;
                }
                indexList.add(new GlobalNewsBean(bean.getTitle(), bean.getID(), bean.getRedirectURL(), bean.getLogo(), style, bean.getPublishDate(), type, Integer.parseInt(bean.getHitCount()), "", bean.getCatalogID(), hasPicture, pOne, pTwo, pThree, bean.getLivetype(), bean.getCommentCount()));
            }
            //加入广告
//            AppContext app = AppContext.getApp();
//            String advlistSwitch = (String) app.getConValue("listAdv");
//            if (advlistSwitch.equals("1") && indexList.size() >= 2 && MPermissionUtils.checkPermissions(this, Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//                QuadNativeAdLoader adLoader = QUAD.getNativeAdLoader(VideoNewsActivity.this, ChannelConfig.PID,
//                        new QuadNativeAdLoadListener() {
//                            @Override
//                            public void onAdLoadSuccess(QuadNativeAd quadNativeAd) {
//                                JSONObject json = quadNativeAd.getContent();
//                                try {
//                                    indexList.add(2, new GlobalNewsBean(json.optString("title"), json.optJSONArray("contentimg").get(0).toString(), "101", json.optInt("action_type", 0), true, quadNativeAd));
//                                } catch (JSONException e) {
//                                    e.printStackTrace();
//                                }
//                                //更新数据源
//                                mDataList.clear();
//                                mDataList.addAll(indexList);
//                                headerAndFooterWrapper.notifyDataSetChanged();
//                            }
//
//                            @Override
//                            public void onAdLoadFailed(int i, String s) {
//                                Log.e("error_adv", s);
//                                //更新数据源
//                                mDataList.clear();
//                                mDataList.addAll(indexList);
//                                headerAndFooterWrapper.notifyDataSetChanged();
//                            }
//                        });
//                if (adLoader != null) {
//                    adLoader.loadAds();
//                }
//
//
//            } else {
            //更新数据源
            mDataList.clear();
            mDataList.addAll(indexList);
            headerAndFooterWrapper.notifyDataSetChanged();
//            }
        } else {
            extendLayout.setVisibility(View.GONE);
        }

    }

    /**
     * 出错
     *
     * @param msg
     */
    @Override
    public void setError(String msg) {
        loadMask.setErrorText(msg);
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 无内容
     *
     * @param msg
     */
    @Override
    public void setEmpty(String msg) {
        loadMask.setEmptyText(msg);
        loadMask.setStatus(LoadingLayout.Empty);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 无网络
     *
     * @param msg
     */
    @Override
    public void setNetError(String msg) {
        loadMask.setNoNetworkText(msg);
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 收藏成功
     *
     * @param msg
     */
    @Override
    public void collectSuccess(String msg) {
        builder.dismiss();
        editbar.setCollect(true);
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
        collectEnable = true;

        //四川融媒统计
        if ((CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145) && mBean != null) {
            StatisticsMainInit.newsInfoCollect(CommonUtils.getInstance().getUserName(), mBean.getID(), mBean.getTitle(), "0");
        }
    }

    /**
     * 收藏失败
     *
     * @param msg
     */
    @Override
    public void collectError(String msg) {
        builder.dismiss();
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
        collectEnable = true;
    }

    /**
     * 取消收藏成功
     */
    @Override
    public void cancelCollectSuccess() {
        builder.dismiss();
        editbar.setCollect(false);
        BusFactory.getBus().post(new Event.CollectMessage(false));
    }

    /**
     * 取消收藏失败
     *
     * @param msg
     */
    @Override
    public void cancelCollectError(String msg) {
        builder.dismiss();
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
        collectEnable = true;
    }

    /**
     * 发送评论成功
     *
     * @param msg
     */
    @Override
    public void sendSuccess(String msg) {


        editbar.changeStateDefault(this);
        editbarEnable = true;

        int commentRule = Integer.parseInt(CommonUtils.getInstance().getCommentRule());
        if (commentRule == 0) {
            Toasty.normal(this, "评论成功！").show();
        } else {
            Toasty.normal(this, "评论成功，等待审核！").show();
        }

        String integralSwitch = CommonUtils.getInstance().getIntergralSwitch();
        if (integralSwitch.equals("1")) {
            getCommentCoin();
        }
    }

    /**
     * 发送评论失败
     *
     * @param msg
     */
    @Override
    public void sendError(String msg) {
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
        editbarEnable = true;
    }

    @Override
    public void cancelCollect() {
        builder.dismiss();
        collectEnable = true;
    }

    @Override
    public void getCoinSuccess(CoinBean bean) {
        coinTimeView.transformation(bean.getCoin() + "", 3);
        if (isLimited) {
            coinTimeView.setEnjoin(true);
            coinTimeView.setProgress(0);
        }
    }

    @Override
    public void getCoinFailure(String msg) {
        Log.i("coin", msg);
        coinTimeView.stopTime();
        coinTimeView.setEnjoin(true);
    }


    @Override
    public void getComCoinSuccess(CoinBean coinBean) {
        Toasty.normal(VideoNewsActivity.this, "成功评论，获得" + coinBean.getCoin() + "金币！").show();
    }

    @Override
    public void getComCoinError(String msg) {
        Log.i("coin_error", msg);
    }

    @Override
    public void likeSuccess() {
        follows++;
        Hawk.put(newsId, 0);
        editbar.isPraise(true);
        editbar.setPraiseNum(follows);
    }

    @Override
    public void likeError(String msg) {
        showToast(msg);
    }

    @Override
    public void cancelLikeSuccess() {
        follows--;
        Hawk.delete(newsId);
        editbar.isPraise(false);
        editbar.setPraiseNum(follows);
    }

    @Override
    public void cancelLikeError(String msg) {
        showToast(msg);
    }

    /**
     * 评论获取金币
     */
    private void getCommentCoin() {
        mPresenter.getCommentCoin("4", "gainCoin");
    }

    @Override
    protected void onResume() {
        super.onResume();
        //baidu
        //umeng
        MobclickAgent.onPageStart("视频详情");
        MobclickAgent.onResume(this);
        videoPlayer.onVideoResume();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.NEWSDETAIL);

        if (integralSwitch.equals("1")) {
            coinTimeView.setRepeat(true);
            if (isLimited) {
                coinTimeView.setEnjoin(true);
                coinTimeView.setProgress(0);
            } else if (Hawk.contains("login")) {
                if (NewsConstant.curProgress != 0) {
                    coinTimeView.setProgress(NewsConstant.curProgress);
                }
                coinTimeView.beginTime();
            } else {
                isFirst = SpfManager.getInstance(this).getBoolean("isFirst", true);
                if (SpfManager.getInstance(this).getBoolean("isFirst", true)) {
                    coinLoginTips.setVisibility(View.VISIBLE);
                    SpfManager.getInstance(this).putBoolean("isFirst", false);
                    coinTimeView.beginTime();
                } else {
                    coinLoginTips.setVisibility(View.GONE);
                }
            }
        }


    }


    @Override
    protected void onPause() {
        super.onPause();
        //baidu
        //umeng
        MobclickAgent.onPageEnd("视频详情");
        MobclickAgent.onPause(this);
        videoPlayer.onVideoPause();
        ActionLogUtils.getInstance().onPause(this, ActionConstant.NEWSDETAIL);
        if (Hawk.contains("login") && integralSwitch.equals("1")) {
            NewsConstant.curProgress = coinTimeView.getProgress();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        videoPlayer.release();
        if (Hawk.contains("login") && integralSwitch.equals("1")) {
            coinTimeView.stopTime();
        }

        BusFactory.getBus().unregister(this);

        //四川融媒统计
        if ((CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145) && mBean != null) {
            StatisticsMainInit.newsInfoVisit(CommonUtils.getInstance().getUserName(), mBean.getID(), mBean.getTitle(), mBean.getReferName(), "1");
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (editbar.getType() == EditBar.TYPE_SEND) {//判断是否是输入状态，是则返回初始状态，否则退出
                    editbar.changeStateDefault(this);
                    return true;
                } else if (GSYVideoManager.backFromWindowFull(this)) {
                    return true;
                } else {
                    finish();
                }
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void commentAdd(Event.commentAdd event) {
        if (event != null) {
            commentNum++;
            editbar.setCommentNum(commentNum);
        }
    }


}
